package com.compass.doctor.ui.mine.fragment

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBFragment
import com.compass.doctor.databinding.FragmentMineBinding
import com.compass.doctor.ui.MainViewModel
import com.compass.doctor.ui.WebDetailActivity
import com.compass.doctor.ui.about.AboutUsActivity
import com.compass.doctor.ui.chat.util.CustomUIConfig
import com.compass.doctor.ui.home.InquiryOrderActivity
import com.compass.doctor.ui.home.adapter.MenuAdapter
import com.compass.doctor.ui.mine.CaSignatureActivity
import com.compass.doctor.ui.mine.DataStatisticsActivity
import com.compass.doctor.ui.mine.DoctorHomepageActivity
import com.compass.doctor.ui.mine.EvaluateActivity
import com.compass.doctor.ui.mine.HospitalizedLogActivity
import com.compass.doctor.ui.mine.InquiryRecordActivity
import com.compass.doctor.ui.mine.IntegralActivity
import com.compass.doctor.ui.mine.PatientFollowActivity
import com.compass.doctor.ui.mine.PrescriptionRecordActivity
import com.compass.doctor.ui.mine.QRCodeActivity
import com.compass.doctor.ui.mine.TestAndInspectionActivity
import com.compass.doctor.ui.mine.view.DoctorInfoView
import com.compass.doctor.ui.mine.viewmodel.IntegralViewModel
import com.compass.doctor.ui.patient.VideoCallActivity
import com.compass.doctor.ui.setting.ConsultSettingActivity
import com.compass.doctor.ui.setting.SettingActivity
import com.compass.framework.constant.AUTHOR_MAIN_LINK
import com.compass.framework.constant.REFRESH_LAUNCH
import com.compass.framework.constant.REFRESH_USER
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toJson
import com.compass.framework.ext.visible
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.MenuItem
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.getStringFromResource
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener


/**
 * 我的主页
 *Date:   2023/11/16 17:04
 */
class MineFragment : BaseVBFragment<FragmentMineBinding>(), OnRefreshListener {
    private val mainViewModel: MainViewModel by activityViewModels()
    private val integralViewModel: IntegralViewModel by viewModels()
    private lateinit var customDoctorInfoView: DoctorInfoView
    private var menuItems: ArrayList<MenuItem> = ArrayList()
    private lateinit var mMenuAdapter: MenuAdapter//功能菜单adapter

    //图文回调
    private val mActivityResultLauncher: ActivityResultLauncher<Intent>? =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            integralViewModel.getDoctorWallet()
        }

    override fun initView(view: View, savedInstanceState: Bundle?) {

        //如果是医生
        if (UserInfoManager.getUserType() == "1") mBinding?.llPrescription?.visible() else mBinding?.llPrescription?.gone()
        initService()
        initDoctorView()
        initMenu()
        initListener()
    }


    //常用服务
    private fun initService() {
        mMenuAdapter = MenuAdapter(2)
        mBinding?.apply {
            refreshLayout.setEnableRefresh(true)
            refreshLayout.setEnableLoadMore(false)
            refreshLayout.setOnRefreshListener(this@MineFragment)
            rcyMenu.apply {
                layoutManager = GridLayoutManager(requireContext(), 4)
                adapter = mMenuAdapter

            }


        }
        mMenuAdapter.onItemClickListener = { view: View, position: Int ->
            serviceClick(menuItems[position].id)
        }

    }

    //头部个人信息
    private fun initDoctorView() {
        customDoctorInfoView = DoctorInfoView(requireContext(), 2)
        mBinding?.flyContainer?.addView(customDoctorInfoView)
    }

    private fun initListener() {
        mBinding?.apply {
            llConcern.onClick {
                PatientFollowActivity.start(requireContext())

            }
            llClinicalReception.onClick {
                InquiryOrderActivity.start(requireContext(), 0)
            }
            ivService.onClick {
                val intent = Intent()
                intent.action = Intent.ACTION_DIAL
                intent.data = Uri.parse("tel:029-5158458")
                startActivity(intent)
            }
            llPrescription.onClick {
                PrescriptionRecordActivity.start(requireContext())
            }
            llMyPatient.onClick {
                mainViewModel.patientLiveData.value = 3
            }
            tvIntegralDetails.onClick {
                //积分详情
                val intent = Intent(requireContext(), IntegralActivity::class.java)
                mActivityResultLauncher?.launch(intent)


            }
            tvServiceTitle.onClick {

                SettingActivity.start(requireContext())
            }
            tvMineAbout.onClick {

                WebDetailActivity.start(
                    context = requireContext(),
                    url = AUTHOR_MAIN_LINK,
                    title = "关于我们"
                )
            }
            tvMineSetting.onClick {
                //设置
                SettingActivity.start(requireContext())
            }
            ivMyCode.onClick {
                QRCodeActivity.start(requireContext())
            }

            tvMineEvaluate.onClick {
                EvaluateActivity.start(requireContext())
            }
        }

    }

    override fun initData() {

        integralViewModel.getDoctorWallet()
        integralViewModel.walletLiveData.observe(this) {
            it?.let { wallet ->
                mBinding?.tvBalanceMoney?.text = String.format("%.2f", wallet.balanceMoney)
                mBinding?.tvFreezeMoney?.text = String.format("%.2f", wallet.freezeMoney)
            }
        }
        mainViewModel.userLiveData.observe(this) { doctorInfo ->
            mBinding?.refreshLayout?.finishRefresh()
            customDoctorInfoView.setDoctorInfo(doctorInfo)
            UserInfoManager.saveUserInfo(doctorInfo?.toJson())
        }
        mainViewModel.todayNumberLiveData.observe(this) {
            it?.let { number ->
                mBinding?.tvPatientNum?.text = number.patientNum.toString()
                mBinding?.tvWaitReceived?.text = number.waitReceived.toString()
                mBinding?.tvPrescriptionNum?.text = number.prescriptionNum.toString()
                mBinding?.tvAttentionNum?.text = number.attentionNum.toString()
            }

        }


    }

     fun getWallet(){
        integralViewModel.getDoctorWallet()
    }
    private fun initMenu() {
        menuItems.add(
            MenuItem(
                2,
                1,
                getStringFromResource(R.string.mine_homepage),
                R.mipmap.mine_homepage
            )
        )
        menuItems.add(
            MenuItem(
                2,
                3,
                getStringFromResource(R.string.mine_inquiry_record),
                R.mipmap.mine_coupon_ico
            )
        )


        //如果是医生
        if (UserInfoManager.getUserType() == "1") {
            menuItems.add(
                MenuItem(
                    2,
                    2,
                    getStringFromResource(R.string.mine_prescription_record),
                    R.mipmap.mine_comment_lab
                )
            )
            menuItems.add(
                MenuItem(
                    2,
                    4,
                    getStringFromResource(R.string.input_menu_inspect),
                    R.mipmap.mine_menu_inspect
                )
            )
            menuItems.add(
                MenuItem(
                    2,
                    5,
                    getStringFromResource(R.string.mine_in_hospital),
                    R.mipmap.mine_in_hospital
                )
            )
        }

        menuItems.add(
            MenuItem(
                2,
                6,
                getStringFromResource(R.string.mine_statistics),
                R.mipmap.mine_statistics
            )
        )
        menuItems.add(
            MenuItem(
                2,
                7,
                getStringFromResource(R.string.mine_consult_setting),
                R.mipmap.mine_consult_setting
            )
        )
//        menuItems.add(
//            MenuItem(
//                2,
//                8,
//                getStringFromResource(R.string.mine_ca_setting),
//                R.mipmap.mine_ac
//            )
//        )
        mMenuAdapter.setData(menuItems)
    }

    private fun serviceClick(id: Int) {
        when (id) {
            1 -> {
                //主页
                DoctorHomepageActivity.start(requireContext())
            }

            2 -> {
                //处方记录
                PrescriptionRecordActivity.start(requireContext())
            }

            3 -> {
                //问诊记录
                InquiryRecordActivity.start(requireContext())
            }

            4 -> {
                //检验检查
                TestAndInspectionActivity.start(requireContext())
            }

            5 -> {
                //住院记录
                HospitalizedLogActivity.start(requireContext())
            }

            6 -> {
                //数据统计
                DataStatisticsActivity.start(requireContext())
            }

            7 -> {
                //咨费设置
                ConsultSettingActivity.start(requireContext())
            }

            8 -> {
                //ca签名
                CaSignatureActivity.start(requireContext())
            }

        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mainViewModel.getUserInfo()
        mainViewModel.orderTodayCount()
        integralViewModel.getDoctorWallet()
    }
}